#include "StdAfx.h"
#include "Camera.h"

namespace Renderer
{

	Camera::Camera()
	{
		Move(0.0f, 0.0f, 0.0f);
		Rotate(0.0f, 0.0f, 0.0f);
		Update();
	}

	D3DXMATRIX * Camera::GetMatrix()
	{
		Update();
		return &worldMatrix;

	}
	void Camera::Update()
	{
		D3DXMatrixMultiply(&worldMatrix, &translationMatrix, &rotationMatrix);
	}

	void Camera::Move(float posX, float posY, float posZ)
	{
		this->posX = posX;
		this->posY = posY;
		this->posZ = posZ;

		D3DXMatrixTranslation(&translationMatrix, -posX, -posY, -posZ);
	}
	void Camera::MoveRel(float addX, float addY, float addZ)
	{
		Move(posX + addX, posY + addY, posZ + addZ);
	}

	void Camera::Rotate(float rotX, float rotY, float rotZ)
	{
		D3DXMATRIX rotXMat, rotYMat, rotZMat;

		this->rotX = rotX;
		this->rotY = rotY;
		this->rotZ = rotZ;

		D3DXMatrixRotationX(&rotXMat, -rotX);
		D3DXMatrixRotationY(&rotYMat, -rotY);
		D3DXMatrixRotationZ(&rotZMat, -rotZ);

		rotationMatrix = rotZMat;
		D3DXMatrixMultiply(&rotationMatrix, &rotationMatrix, &rotYMat);
		D3DXMatrixMultiply(&rotationMatrix, &rotationMatrix, &rotXMat);
	}

	void Camera::RotateRel(float addX, float addY, float addZ)
	{
		Rotate(rotX + addX, rotY + addY, rotZ + addZ);
	}

	void Camera::Point(float eyeX, float eyeY, float eyeZ, float atX, float atY, float atZ)
	{
		float rotX, rotY, diffX, diffY, diffZ;

		diffX = atX - eyeX;
		diffY = atY - eyeY;
		diffZ = atZ - eyeZ;

		rotX = (float)atan2(-diffY, sqrt(diffX * diffX + diffZ * diffZ));
		rotY = (float)atan2(diffX, diffZ);

		Move(eyeX, eyeY, eyeZ);
		Rotate(rotX, rotY, 0.0f);
	}

	void Camera::SetStartTrack()
	{
		startPosX = posX;
		startPosY = posY;
		startPosZ = posZ;

		startRotX = rotX;
		startRotY = rotY;
		startRotZ = rotZ;
	}
	void Camera::SetEndTrack()
	{
		endPosX = posX;
		endPosY = posY;
		endPosZ = posZ;

		endRotX = rotX;
		endRotX = rotY;
		endRotX = rotZ;
	}

	void Camera::Track(float time, float duration)
	{
		float x, y, z;
		float timeOffset = duration * time;

		x = (endPosX - startPosX) / duration * timeOffset;
		y = (endPosY - startPosY) / duration * timeOffset;
		z = (endPosZ - startPosZ) / duration * timeOffset;
		Move(startPosX + x, startPosY + y, startPosZ + z);

		x = (endRotX - startRotX) / duration * timeOffset;
		y = (endRotY - startRotY) / duration * timeOffset;
		z = (endRotZ - startRotY) / duration * timeOffset;
		Rotate(startRotX + x, startRotY + y, startRotZ + z);
	}

	float Camera::GetXPos() const { return posX; }
	float Camera::GetYPos() const { return posY; }
	float Camera::GetZPos() const { return posZ; }
	float Camera::GetXRotation() const { return rotX; }
	float Camera::GetYRotation() const { return rotY; }
	float Camera::GetZRotation() const { return rotZ; }


}